package com.ryskoo.catering.ordermain.repository;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ryskoo.common.constant.EurekaServiceName;
import com.ryskoo.common.dto.customer.VendorIndexInfo;
import com.ryskoo.framework.core.utils.RedisUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisQueue {
    private static final Logger logger = LogManager.getLogger(EurekaServiceName.CATERING_SERVICE);

    private static final String KEY = "ORDER_QUEUE";

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    RedisUtil redisUtil;

    public void pushMessage(OrderMessage message) {
        ListOperations<String, String> op = redisTemplate.opsForList();
        op.leftPush(KEY, JSON.toJSONString(message));
    }

    @Scheduled(initialDelay = 5000L, fixedDelay = 1000L)
    public void processMessage() {
        ListOperations<String, String> op = redisTemplate.opsForList();
        String str = op.rightPop(KEY, 5, TimeUnit.SECONDS);
        if (null != str) {
            try {
                OrderMessage message = JSON.parseObject(str, new TypeReference<OrderMessage>() {
                });
                updateVendorIndexInfo(message);
            } catch (Exception e) {
                logger.error("处理订单队列消息失败", e);
                // 将消息重新放回队列
                op.leftPush(KEY, str);
            }
        }
    }

    private void updateVendorIndexInfo(OrderMessage message) {
        String date = message.getOrderTime().substring(0, 10);
        VendorIndexInfo indexInfo = (VendorIndexInfo) redisUtil.getObject(message.getVendorUuid() + "_" + date);
        if (null == indexInfo) {
            indexInfo = new VendorIndexInfo(message.getVendorUuid(), date, message.getAmount(), 1, message.getPeople());
        } else {
            if (1 == message.getType()) {
                indexInfo.setIncome(indexInfo.getIncome() + message.getAmount());
                indexInfo.setQuantity(indexInfo.getQuantity() + 1);
                indexInfo.setPeople(indexInfo.getPeople() + message.getPeople());
            } else {
                indexInfo.setIncome(indexInfo.getIncome() - message.getAmount());
                indexInfo.setQuantity(indexInfo.getQuantity() - 1);
                indexInfo.setPeople(indexInfo.getPeople() - message.getPeople());
            }
        }
        redisUtil.setExpireObject(message.getVendorUuid() + "_" + date, indexInfo, 8L, TimeUnit.DAYS);
    }
}
